$.lp = {
    videoLink:"",
    action:"",
    mediaTitle:"",
    mediaDesc:"",
    mediaThumb:"",
    mediaID:"",
    hd:false,
    text:"",
    identifier:"",
    init: function(){
        $('.shareTextarea textarea').autosize();  
        $("header").addClass('headerProfile');
        // Get Photo Overlay on Click
        $("#shareMood").on('click',function(){
            var message = $(".shareTextarea").find("textarea").val();
            $.post("profile/mood", {moodMessage : message},function(data){
                if(data){
                    $(".shareTextarea").find("textarea").val("").focusout();
                    $(".mood").find("p").text(message);
                }
            });
        });
        $('html').click(function(e) {
            if(!$(e.target).hasClass('editPost'))
                $('.editPost').hide();
        });
        $('.profileVideos, .photo').on({mouseenter:function(){
            $(this).find('.editPost').show();
        },mouseleave:function(){
            if($(this).find('.editPost').next().is(":hidden"))
                $(this).find('.editPost').hide();
        }});
        $('.editPost').on('click',function(){
            $('.editPost').not(this).hide();
            $('.editPost').not(this).next().hide();
            $(this).next().show();
            return false;  
        });
        $('.deletePost').on('click',function(){
            var this_ = $(this);
            var id = $(this).parents('.editPostWrapper').next().find("a").attr('id');
            var type = $(this).parents('.editPostWrapper').next().find("a").attr('class').replace("Post","");
            $.post("profile/deletePost", {id : id,type:type},function(data){
                if(data){
                    this_.parents("article").remove();
                }
            });
        });
        $(".photoPost").on('click',function(){

            var id = $(this).attr("id");
            var title="";
            var image = "";
            var name = "";
            var user_profile_img = "";
            var uploaded = "";
            var photograph = "";
            $.getJSON("photos/xhrPhoto", {id:id}, function(data){
               var template = $('#photoOverlay_template').html();
               var img = '<img src="'+data.source+'" alt="'+data.title+'" />';
               image = img;
               title = data.title;
               uploaded = data.uploaded;
               photograph = data.photograph;
               $.getJSON("users/getUser", {user_id:data.user_id}, function(user){
                    name = user.first_name+" "+user.last_name;
                    user_profile_img = '<img src="'+user.profile_pic+'" alt="'+user.first_name+" "+user.last_name+'" width="100px"/>';
                    var data = {
                        image : image,
                        title : title,
                        name:name,
                        profile_img:user_profile_img,
                        date: uploaded,
                        photographer : photograph
                    };
                    var html = Mustache.to_html(template, data);
                    $('#LeapMainWrapper').after(html);
                    $(".photo_overlay").show();
                    $('.overlay_bg').show();
               });
            });
            return false;
        });
        // Close Photo Overlay
        $('.close_overlay').on('click',function(){
            $('.photo_overlay').remove();
            $('.overlay_bg').hide();
        });
        // Profile Navigation On Click Handler
        $(".profileNavigation").find('li').on('click',function(){
            $(".profileNavigation").find('.selected').removeClass('selected');
            $(this).addClass('selected');
            var identifier = $(this).attr('id');
            var profile_id = $('.profileContent').attr("id");
            $(".feed").empty().hide();
            var loading = "<div class='loading'><img src='public/images/lc_loading.gif' alt='loading' /></div>"
            $("."+identifier+"Wrapper").show().html(loading);
            $.getJSON("profile/get"+identifier+"FromID?profile_id="+profile_id, function(data){
                var template;
                var index = 0;
                    var articel1 = [];
                    var articel2 = [];
                    var articel3 = [];
                    var articel4 = [];
                    var articel = {}
                if(identifier === "photos"){
                    template = $('#photos_template').html();
                    $.each(data,function(key,value){
                        if(index == 0){
                            articel1.push(value);
                            index++;
                        }
                        else if(index ==1){
                            articel2.push(value);
                            index++;
                        }
                        else if(index ==2){
                            articel3.push(value);
                            index++;
                        }
                        else if(index ==3){
                            articel4.push(value);
                            index = 0;
                        }
                        articel = {
                        articel1:articel1,
                        articel2:articel2,
                        articel3:articel3,
                        articel4:articel4
                    }
                    });
                }
                if(identifier === "videos"){
                    template = $('#videos_template').html();
                    articel = {
                        videos:data.videos
                    }
                }
                
                var html = Mustache.to_html(template, articel);
                $("."+identifier+"Wrapper").empty().html(html);
                $('html,body').delay(500).animate({scrollTop:$(".profileNavigation").offset().top-10});
            });
        });
        $('.uploadPic').on('change', function(){ 
            var bar = $('.bar');
            var status = $('.preview');
            $(this).parents("form").ajaxForm({
                target: '.preview',
                beforeSend: function() {
                    status.empty();
                    var percentVal = '0%';
                    bar.width(percentVal)
                },
                uploadProgress: function(event, position, total, percentComplete) {
                    var percentVal = percentComplete + '%';
                    bar.width(percentVal)
                },
                complete: function(xhr) {
                    status.html(xhr.responseText);
                }
            }).submit();
		
        });
        
        $('.uploadImage').on('change', function(){ 
            var bar = $('.bar');
            //var status = $('.preview');
            $(this).parents("form").ajaxForm({
                //target: '.preview',
                dataType:  'json', 
                beforeSend: function() {
                    var percentVal = '0%';
                    bar.width(percentVal)
                },
                uploadProgress: function(event, position, total, percentComplete) {
                    var percentVal = percentComplete + '%';
                    bar.width(percentVal)
                },
                complete: function(xhr) {
                    if(xhr.responseText === "<p>The uploaded file exceeds the maximum allowed size in your PHP configuration file.</p>")
                        xhr.responseText = "<p>The uploaded file is Too Big.</p>";
                    
                    $('.uploadImage').parent().hide();
                    $("#shareImage").show();
                },
                success: function(data){
                    $('.preview').find("form").html(data.content);
                    $('.preview').find("form").find("#imgID").val(data.image_id);
                    $('.preview').find("form").find(".imagePlaceholder").html("<img src='"+data.image_source+"' alt='Uploaded Image' width='350'/>");
                }
            }).submit();
		
        });
        
        $('.close_overlay').on('click',function(){
            $('#overlay_share').remove();
            $(".upload_overlay").hide();
            $('.overlay_bg').hide();
        });
        $("#500px_").on('click',function(){
            $("#share500pxPhoto").show();
            $("#photoUpload").hide();
            $("#editImage").hide();
        });
        $("#uploadImage_").on('click',function(){
            $("#share500pxPhoto").hide();
            $("#editImage500px").hide();
            $("#photoUpload").show();
            $("#editImage").show();
        });
      $('.videoStream').find(".videoPost").on('click',function(event){
            var id = $(this).attr('id');
            var vimeo = "vimeo";
            var videoEmbed;
            if($(this).find('img').attr('src').indexOf(vimeo) != -1)
                videoEmbed =   '<iframe src="http://player.vimeo.com/video/'+id+'" width="265px" height="199px" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>';
            else
                videoEmbed = '<iframe class="youtube-player" type="text/html" width="265px" height="199px" src="http://www.youtube.com/embed/'+id+'?autoplay=1" frameborder="0"></iframe>';
            $(this).parent().empty().html(videoEmbed);
            return false;
        });
    },
    shareVideo: function(){
        // Video Icon Click
        $(".videoIco").on('click',function(){
            var template = $('#share_template').html();
            var data = {
              header:'Share Video',
              action:'shareVideo',
              video:true
            };
            var html = Mustache.to_html(template, data);
            $('#LeapMainWrapper').after(html);
            $('.overlay_bg').show();
            $('#overlay_share').show();
//            $('#overlay_share').find(".overlay_head p").text("Share Video");
//            var action = $('#overlay_share').find("#shareform").attr('action');
//            $.lp.action = action+'shareVideo';
//            $('#overlay_share').find("#shareform").attr('action',action+"shareVideo");
            
            return false;
        });
        // Photo Icon Click
        $(".pictureIco").on('click',function(){
            var template = $('#share_template').html();
            var data = {
              header:'Share Photo',
              action:'upload_image',
              picture:true
            };
            var html = Mustache.to_html(template, data);
            $('#LeapMainWrapper').after(html);
            $('.overlay_bg').show();
            $('#overlay_share').show();
//            $('#overlay_share').find(".overlay_head p").text("Share Video");
//            var action = $('#overlay_share').find("#shareform").attr('action');
//            $.lp.action = action+'shareVideo';
//            $('#overlay_share').find("#shareform").attr('action',action+"shareVideo");

            return false;
        });

        $(".shareTextarea").find("input").on('focus',function(){
             $(this).prev().text("");
        });
        $(".shareTextarea").find(".placeholder").on('click',function(){
            $(this).next().focus();
        });
        $(".shareTextarea").find("textarea").on('focus',function(){
            if($(this).val() === ""){
                $.lp.text = $(this).next().text();
                $(this).next().text("");
                $(this).parents('.shareSome').find('#shareMood').css("display", "block");
            }
        });
        $(".shareTextarea").find("textarea").on('focusout',function(){
             if($(this).val() === ""){
                $(this).next().text($.lp.text);
                $(this).parents('.shareSome').find('#shareMood').css("display", "none");
             }
        });
        $("#shareYoutubeVideo").find("input").on('change',function(){
                
                var _videoUrl = $(this).val();
                var code = getEmbeddedPlayer(_videoUrl);
                if (code)
                {
                    $.getJSON("http://gdata.youtube.com/feeds/api/videos/"+code+"?v=2&alt=json", function(data){
                        $.lp.mediaTitle = data.entry.title.$t;
                        $.lp.mediaDesc = data.entry.media$group.media$description.$t;
                        $.lp.mediaThumb = data.entry.media$group.media$thumbnail[2].url;
                        $.lp.mediaID = data.entry.media$group.yt$videoid.$t;
                        $.lp.identifier = "youtube";
                        if(data.entry.yt$hd)
                            $.lp.hd = true;
                        $(".previewMedia").show();
                        $(".previewMedia").find("h4.title").empty().append(data.entry.title.$t);
                        $(".previewMedia").find(".thumbnail").empty().append("<img width='300' src='"+data.entry.media$group.media$thumbnail[2].url+"' alt='"+data.entry.title+"'/>");
                        $(".previewMedia").find(".link").empty().append("<a href='https://www.youtube.com/watch?v='"+data.entry.media$group.yt$videoid.$t+"'>https://www.youtube.com/watch?v='"+data.entry.media$group.yt$videoid.$t+"</a>");
                        $(".previewMedia").find(".description").empty().append(data.entry.media$group.media$description.$t);
                        $("#shareMedia").removeClass("disabled");
                    });
                }
             
        });
        //Vimeo
        $("#shareVimeoVideo").find("input").on('change',function(){
                var _videoUrl = $(this).val();
                var code = getEmbeddedPlayer(_videoUrl);
                if (code)
                {
                    $.getJSON("http://vimeo.com/api/v2/video/"+code+".json?callback=?", {format: "json"}, function(data){
                        $.lp.mediaTitle = data[0].title;
                        $.lp.mediaDesc = data[0].description;
                        $.lp.mediaThumb = data[0].thumbnail_large;
                        $.lp.mediaID = data[0].id;
                        $.lp.identifier = "vimeo";
                        $(".previewMedia").show();
                        $(".previewMedia").find("h4.title").empty().append($.lp.mediaTitle);
                        $(".previewMedia").find(".thumbnail").empty().append("<img width='300' src='"+$.lp.mediaThumb+"' alt='"+$.lp.mediaTitle+"'/>");
                        $(".previewMedia").find(".link").empty().append("<a href='http://vimeo.com/'"+$.lp.mediaID+"'>http://vimeo.com/'"+$.lp.mediaID+"</a>");
                        $(".previewMedia").find(".description").empty().append($.lp.mediaDesc);
                        $("#shareMedia").removeClass("disabled");
                    });
                }

        });
        $("#shareMedia").on('click',function(){
            var action = $(this).parents('#shareform').attr("action");
            
            if(!$(this).hasClass('disabled')){
                $.post(action,{
                    title:$.lp.mediaTitle,
                    desc:$(".previewMedia").find("textarea").val(),
                    thumb:$.lp.mediaThumb,
                    id:$.lp.mediaID,
                    hd:$.lp.hd,
                    identifier:$.lp.identifier
                },function(data){
                    if(data){
                        $('.overlay_bg').hide();
                        $('#overlay_share').remove();
                    }
                    });
            }
        });
        $(".overlay_content_side").find('li').on('click',function(){
             $(".overlay_content_side").find('li.selected').removeClass('selected');
             $(this).addClass('selected');
             if($(this).attr('id') == "youtube_"){
                $('#shareYoutubeVideo').show();
                $('#shareVimeoVideo').hide();
             }
             else if($(this).attr('id') == "vimeo_"){
                $('#shareVimeoVideo').show();
                $('#shareYoutubeVideo').hide();
             }
             else{
                 
             }
        });
        
    },
    shareImage : function(){
        $("#share500pxPhoto").find("input").on('change',function(){
            var substr = $(this).val().split('<img');
            var img =    substr[1].split('</a>');
            
            $('#editImage500px').show().find("form").find(".imagePlaceholder").html("<img"+ img[0]);
            $("#shareImage500px").show();
            $("#share500pxPhoto").hide();
        });
        $("#shareImage500px").on('click',function(){
            var action = $(this).prev().find('form').attr('action');
            var image = $(this).prev().find('form').find(".imagePlaceholder").find("img").attr('src');
            var original = image.replace("/3.","/4.");
            var image_title = $(this).prev().find('form').find("#imgTitle").val();
            var image_desc = $(this).prev().find('form').find("#imgDesc").val();
            var image_photograph = $(this).prev().find('form').find("#photograph").val();
            $.ajax({  
                type: "POST",  
                url: action,  
                data: {
                    thumb:image,
                    source: original,
                    title : image_title,
                    desc : image_desc,
                    photograph : image_photograph
                },  
                success: function(data) {  
                    if(data === "1"){
                        $('.overlay_bg').hide();
                        $('#overlay_share').remove();
                    }  
                }  
            });  
            return false;
        })
        $("#shareImage").on('click',function(){
            var action = $(this).prev().find('form').attr('action');
            var image_id = $(this).prev().find('form').find("#imgID").val();
            var image_title = $(this).prev().find('form').find("#imgTitle").val();
            var image_desc = $(this).prev().find('form').find("#imgDesc").val();
            var photograph = $(this).prev().find('form').find("#photograph").val();
            $.ajax({  
                type: "POST",  
                url: action,  
                data: {
                    id:image_id,
                    title : image_title,
                    desc : image_desc,
                    photograph : photograph
                },  
                success: function(data) {  
                    if(data === "1"){
                        $('.overlay_bg').hide();
                        $('#overlay_share').hide();
                    }  
                }  
            });  
            return false;
        });
    }
}

function getEmbeddedPlayer(url){
    
	//var output = '';
	var youtubeUrl = url.match("[\?&]v=([^&#]*)");
	var vimeoUrl = url.match(/^http:\/\/(www\.)?vimeo\.com\/(clip\:)?(\d+).*$/);
	if( youtubeUrl ){
		//output = '<iframe width="'+width+'" height="'+height+'" src="http://www.youtube.com/embed/'+youtubeUrl[1]+'?rel=0" frameborder="0" allowfullscreen>';
                return youtubeUrl[1];
	}else if(vimeoUrl){
		//output =  '<iframe src="http://player.vimeo.com/video/'+vimeoUrl[3]+'" width="'+width+'" height="'+height+'" frameborder="0"></iframe>';
                return vimeoUrl[3];
	}else{
		//output = '<p>no video url found - vimeo and youtube supported</p>';
                return false;
	}
//	return output;
}